//
//  main.c
//  C_12线程
//
//  Created by Robin on 16/3/22.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int beers = 200000;
pthread_mutex_t a_lock = PTHREAD_MUTEX_INITIALIZER;

void error (char *msg){
    fprintf(stderr, "%s:%s\n",msg,strerror(errno));
    exit(1);
}
// void * 指针和 long 大小相同
void *drink_losts (void *a){
    
    pthread_mutex_lock(&a_lock);

    for (int i=0; i<10000; i++) {
        beers = beers -1;
    }
    
    pthread_mutex_unlock(&a_lock);
    printf("There are now %i bottles of beer on the wall\n",beers);

    return NULL;
}

int main(int argc, const char * argv[]) {

    pthread_t threads[20];
    
    int t;
    printf("%i bottles of beer on the wall\n %i bottles of beers\n",beers,beers);
    
    for (t=0; t<20; t++) {
        if (pthread_create(&threads[t], NULL, drink_losts, NULL) == -1) {
            printf("无法创建线程 %i\n",t);
        }
    }
    
    void *result;
    
    for (t=0; t<20; t++) {

        if (pthread_join(threads[t], &result) == -1) {
            printf("无法回收线程 %i\n",t);
        }
    }
    
    return 0;
}
